package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat


public class apiAutoGetU9ItemList implements ServiceBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(apiAutoGetU9ItemList.class);
    int timeout = 30000;
    int enableSSLflag = 0;
    String charset = "utf-8";
    String v_starttime = '';
    Map<String, Object> headMap = new HashMap<>(); // 请求参数头
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        /*
       获取U9获取商品列表(商品明细) -- demi
           防止 定时任务同一时间 多次执行
           设计最大执行时间范围 开始执行后立即更新下次允许执行时间 在此期间 禁止重复执行

        */
        String sql0 = """
            select    case when  now() >next_executedate   then  1 else 0 end  as flag from  interface_lock where interfaceName = 'apiAutoGetU9ItemList'
        """;
        // 查询是否有已经在执行的定时任务或者 或者之前的上次定时任务异常结束
        int flag = eliteBean.chaxun_sql(sql0, "dataSource").get(0).get("flag");

        log.debug("flag: ", flag);

        if (flag == 0) {
            log.debug(" apiAutoGetU9ItemList 获取U9获取商品列表(商品明细) ： 未到下次执行时间 不予执行");
            return "success";
        } else {
            // 立即数据库标记正在执行  频率内不重复执行
            eliteBean.update("update interface_lock set last_executedate = now(),next_executedate =STR_TO_DATE( date_add(now(), interval frequency*60 second),'%Y-%m-%d %H:%i:%s') where interfaceName = 'apiAutoGetU9ItemList'", "dataSource");
        };

        Date date1 = new Date();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        v_starttime = sdf.format(date1);
        log.debug(" 开始时间"+v_starttime);

        headMap.put("Content-Type", "application/json;charset=UTF-8");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        log.warn("---apiAutoGetU9ItemCategoryList 开始---");

        try {
            // 获取token
            String querySQL1 = "select string3 as token from sysc_interface where method='getU9Token' ";
            String token = eliteBean.chaxun_sql(querySQL1, "dataSource").get(0).get("token");

            log.debug("当前token：" + token);
            headMap.put("Authorization", "Bearer " + token);
            // 获取接口地址
            String querySQL2 = "select url  from sysc_interface where method='GetU9ItemList' ";
            String url = eliteBean.chaxun_sql(querySQL2, "dataSource").get(0).get("url");


            // 获取商品类别

            String querySQL3 = "select code ,name  from ItemCategoryList where 1=1 ";
            List productList = eliteBean.chaxun_sql(querySQL3, "dataSource");


            // 数据 备份 再删除
            String[] arr = new String[2];

            // 差 2句 sql

            arr[0] = "insert into ItemList_log(log_guid,product_guid,ItemCode,ItemName,SPECS,UOM,GrossWeight,NetWeight,Category,Volume,ValidityTerm,CatalogNO,status,ItemList_createddate,createddate) " +
                    "   select uuid(),product_guid,ItemCode,ItemName,SPECS,UOM,GrossWeight,NetWeight,Category,Volume,ValidityTerm,CatalogNO,status,createddate,now()  from ItemList ";
            arr[1] = "delete  from  ItemList where 1=1";

            // ItemCategoryList_log
            int[] result = eliteBean.updateBatch(arr, 'dataSource');

            log.debug("U9商品列表数据备份结果：" + result.toString());

            log.debug("productList：" + productList.toString());

            if (productList.size() > 0) {

                for (int i = 0; i < productList.size(); i++){
                    String code = productList.get(i).get("code");
                    log.debug("code：" + code);
                    getProcuntInfo(eliteBean,url,code);
                }

            } else {

                log.debug("无产品类别 不获取商品信息！！！");
            };

            // 执行记录
            String sql99 =  "insert into p_errorlog(v_return,v_interfanceName,v_type,v_starttime,v_endtime,v_errordesc,v_parameter1,v_parameter2)  "+
                    "values('1','apiAutoGetU9ItemList','1', STR_TO_DATE('"+v_starttime+"' ,'%Y/%m/%d %H:%i:%s')  ,now(),'执行成功','','') ";
            log.debug("sql99: "+sql99);
            eliteBean.update(sql99, "dataSource");

        } catch (Exception e) {

            log.error("获取U9获取商品列表(商品明细)异常", Util.getERRO(e));

            def v_parameter2;
            def v_length= Util.getERRO(e).toString().length();
            log.debug("v_length: ",v_length);
            if( v_length>2500)  {
                v_parameter2 =Util.getERRO(e).substring(0, 2500).replace("'", "\\");
            }

            if( v_length<=2500 && v_length>0)  {
                v_parameter2 =Util.getERRO(e).substring(0, v_length-1).replace("'", "\\");
            }
            // 执行记录
            String sql99 =  "insert into p_errorlog(v_return,v_interfanceName,v_type,v_starttime,v_endtime,v_errordesc,v_parameter1,v_parameter2)  "+
                    "values('-1','apiAutoGetU9ItemList','1',STR_TO_DATE('"+v_starttime +"', '%Y/%m/%d %H:%i:%s') ,now(),'接口异常2','','"+v_parameter2+"')";
            log.debug("sql99: "+sql99);
            eliteBean.update(sql99, "dataSource");

        };

        log.debug("获取U9获取商品列表(商品明细) 耗时：" + ((long) new Date().getTime() - (long) date1.getTime()) + "毫秒");

        return "success";
    };

    // 调用接口 获取商品详细信息
    public String getProcuntInfo(EliteBean eliteBean, String url, String code ) {


        try {

            String requestBody = url + 'ItemClass=' + code + '&ItemCode=&ItemName=';
            log.debug("apiAutoGetU9ItemList-----getProcuntInfo--------requestBody:" + requestBody);
            String responseInfo = Util.doHttpGetUseHead(requestBody, charset, timeout, enableSSLflag, headMap);
            log.debug("apiAutoGetU9ItemList-----getProcuntInfo--------responseInfo:" + responseInfo);
            JSONArray resArr = JSONArray.fromObject(responseInfo);

            if (resArr.size() > 0) {

                String sql = '';
                // 解析接口 保存数据
                for (int i = 0; i < resArr.size(); i++) {

                    String ItemCode = resArr[i].ItemCode;
                    String ItemName = resArr[i].ItemName;
                    String SPECS = resArr[i].SPECS;
                    String UOM = resArr[i].UOM;
                    String GrossWeight = resArr[i].GrossWeight;
                    String NetWeight = resArr[i].NetWeight;
                    String Category = resArr[i].Category;
                    String Volume = resArr[i].Volume;
                    String ValidityTerm = resArr[i].ValidityTerm;
                    String CatalogNO = resArr[i].CatalogNO;

                    if(!ItemCode){
                        ItemCode = '';
                    }
                    if(!ItemName){
                        ItemName = '';
                    }
                    if(!SPECS){
                        SPECS = '';
                    }
                    if(!UOM){
                        UOM = '';
                    }
                    if(!GrossWeight){
                        GrossWeight = '';
                    }
                    if(!NetWeight){
                        NetWeight = '';
                    }
                    if(!Category){
                        Category = '';
                    }
                    if(!Volume){
                        Volume = '';
                    }
                    if(!ValidityTerm){
                        ValidityTerm = '';
                    }
                    if(!CatalogNO){
                        CatalogNO = '';
                    };

                    log.debug("apiAutoGetU9ItemList-----CatalogNO:" + CatalogNO);
                    sql = "insert into ItemList(product_guid,ItemCode,ItemName,SPECS,UOM,GrossWeight,NetWeight,Category,Volume,ValidityTerm,CatalogNO,status,createddate) values(  uuid(),'"+
                    ItemCode + "','" + ItemName + "','" + SPECS + "','" + UOM + "','" + GrossWeight + "','" + NetWeight + "','" + Category + "','" + Volume + "','" + ValidityTerm + "','" + CatalogNO + "','1',now())";
                    log.debug("apiAutoGetU9ItemList-----sql:" + sql);

                    int res = eliteBean.update(sql, "dataSource");
                    int num = i + 1;
                    log.debug("获取U9获取商品列表(商品明细) 保存第" + num + "次结果: " + res);

                };
            };

            return "ok"

        } catch (Exception e) {

            log.debug("获取商品信息异常： " + Util.getERRO(e));

            def v_parameter2;
            def v_length= Util.getERRO(e).toString().length();
            log.debug("v_length: ",v_length);
            if( v_length>2500)  {
                v_parameter2 =Util.getERRO(e).substring(0, 2500).replace("'", "\\");
            }

            if( v_length<=2500 && v_length>0)  {
                v_parameter2 =Util.getERRO(e).substring(0, v_length-1).replace("'", "\\");
            }
            // 执行记录
            String sql99 =  "insert into p_errorlog(v_return,v_interfanceName,v_type,v_starttime,v_endtime,v_errordesc,v_parameter1,v_parameter2)  "+
                    "values('-1','apiAutoGetU9ItemList','1',STR_TO_DATE('"+v_starttime +"', '%Y/%m/%d %H:%i:%s') ,now(),'接口异常1','','"+v_parameter2+"')";
            log.debug("sql99: "+sql99);
            eliteBean.update(sql99, "dataSource");
        }
    }
}
